/**
* @file  HoverMask 组件编辑器hover遮罩
* @author xiao_xie
* @date 2025-03-18
*/


import classNames from 'classnames';
import React, { useEffect, useMemo } from 'react';
import useComponentStore, { findComponentById } from '../../../store';
import { createPortal } from 'react-dom';
interface Props {
    componentId: string; // 组件dom的id
    componentWrapper: string; // 组件的wrapper的calss
    maskWrapper: string; // 要渲染dom组件的wrapper的calss
}

interface PositionType {
    top: number;
    left: number;
    width: number;
    height: number;
}

const HoverMask: React.FC<Props> = ({ componentId, componentWrapper, maskWrapper }) => {

    const [position, setPosition] = React.useState<PositionType>({ top: 0, left: 0, width: 0, height: 0 }) // 组件的位置
    const { components } = useComponentStore();

    // 根据id查找组件，获取组件的描述
    const curComponet = useMemo(() => findComponentById(Number(componentId), components), [componentId])


    const handlePositsion = () => {
        const elem = document.querySelector(`[data-component-id="${componentId}"]`);
        const wrapper = document.querySelector(`.${componentWrapper}`);
        if (!wrapper) return;
        const { left: warpperLeft, top: warpperTop } = wrapper.getBoundingClientRect();
        if (elem) {
            const { width, height, left, top } = elem.getBoundingClientRect();
            setPosition({
                width, height,
                left: left - warpperLeft,
                top: top - warpperTop
            })
        }
    }

    useEffect(() => {
        handlePositsion();
    }, [componentId])

    const cls = classNames(['absolute border-2 border-[#6366F1] rounded-md border-solid cursor-pointer z-10'])
    const el = useMemo(() => {
        return document.querySelector(`.${maskWrapper}`)!;
    }, [maskWrapper]);

    return el ? createPortal((
        <>
            <div className={cls}
                style={{
                    pointerEvents: "none", // 除了指示该元素不是鼠标事件的目标之外，值none表示鼠标事件“穿透”该元素并且指定该元素“下面”的任何东西。
                    left: position.left + 'px',
                    top: position.top + 'px',
                    width: position.width + 'px',
                    height: position.height + 'px',
                    zIndex: 12,
                }}>
                <div className='absolute right-0 top-[-16px] text-white bg-[#6366F1] text-xs px-3 rounded-sm'>
                    {curComponet?.desc}
                </div>
            </div>
        </>
    ), el) : null
};
export default HoverMask;
